#!/bin/bash
# SPDX-License-Identifier: Apache-2.0
# Copyright Authors of Cilium

DIR=$(dirname $(readlink -ne $BASH_SOURCE))
source $DIR/../release/lib/common.sh
source $DIR/common.sh

require_linux

if ! hub help | grep -q "api"; then
    echo "This tool relies on a recent version of 'hub' from https://github.com/github/hub." 1>&2
    echo "Please install this tool first." 1>&2
    exit 1
fi

BRANCH="${1:-}"
if [ "$BRANCH" = "" ]; then
    BRANCH=$(git symbolic-ref --short HEAD | sed 's/.*\(v[0-9]\+\.[0-9]\+\).*/\1/')
fi
BRANCH=$(echo "$BRANCH" | sed 's/^v//')

SUMMARY=${2:-}
if [ "$SUMMARY" = "" ]; then
    SUMMARY="v$BRANCH-backport-$(date --rfc-3339=date).txt"
fi

USER_REMOTE=$(get_user_remote ${3:-})

UPSTREAM_REMOTE=$(get_remote)
if ! git branch -a | grep -q "${UPSTREAM_REMOTE}/v${BRANCH}$" || [ ! -e "$SUMMARY" ]; then
    echo "usage: $0 [branch version] [pr-summary] [your remote]" 1>&2
    echo 1>&2
    echo "Ensure 'branch version' is available in 'upstream remote'/cilium and the summary file exists" 1>&2
    echo "(branch version: ${BRANCH}, pr-summary: ${SUMMARY}, upstream remote: ${UPSTREAM_REMOTE})" 1>&2
    exit 1
fi

AUTHORS="$(grep -ho "@[^)]*" "$SUMMARY" | grep -v "$(get_user)" | sort -u | tr '\n' ' ' | sed -e 's/@//g' -e 's/ $//')"

# Github complains if we request a review by someone who is not a collaborator, thus filter the authors.
REVIEWERS=""
for author in $AUTHORS; do
    if [ $(is_collaborator "$author") == "yes" ]; then
        REVIEWERS="$REVIEWERS,$author"
    fi
done
REVIEWERS=${REVIEWERS:1} # Lop off the initial comma.

echo -e "Sending PR for branch v$BRANCH:\n" 1>&2
cat $SUMMARY 1>&2
echo -e "\nSending pull request..." 2>&1
PR_BRANCH=$(git rev-parse --abbrev-ref HEAD)
git config --local "branch.${PR_BRANCH}.remote" "$USER_REMOTE"
git push -q "$USER_REMOTE" "$PR_BRANCH"
if [ -z "$REVIEWERS" ]; then
  hub pull-request -b "v$BRANCH" -l kind/backports,backport/$BRANCH -F $SUMMARY
else
  hub pull-request -b "v$BRANCH" -l kind/backports,backport/$BRANCH -F $SUMMARY -r $REVIEWERS
fi

prs=$(grep "contrib/backporting/set-labels.py" $SUMMARY | sed -e 's/^.*for pr in \([0-9 ]\+\);.*$/\1/g')
echo -e "\nUpdating labels for PRs $prs\n" 2>&1
echo -n "Set labels for all PRs above? [Y/n] "
read set_all_labels
if [ "$set_all_labels" != "n" ]; then
    for pr in $prs; do
        $DIR/set-labels.py $pr pending $BRANCH;
    done
fi
